package main

import (
	"fmt"
	"net/http"
	_ "net/http/pprof"
	"os"
	"time"
)

func main() {
	//启动一个http端口
	go func() {
		ip := "0.0.0.0:6060"
		if err := http.ListenAndServe(ip, nil); err != nil {
			fmt.Printf("start pprof failed on %s\n", ip)
			os.Exit(1)
		}
	}()

	outCh := make(chan int)
	stime := time.Now()
	// 每1s个goroutine
	for {
		time.Sleep(100 * time.Millisecond)
		//每个goroutine分配1M内存，本来内存在goroutine退出以后会自动释放，不存在泄漏的问题，
		//但是由于outCh只有写入没有读取导致channel写入阻塞，整个goroutine阻塞在alloc这行，导致分配的内存没有释放，形成内存泄漏
		go alloc(outCh)
		fmt.Printf("last: %dseconds\n", int(time.Now().Sub(stime).Seconds()))
	}
}

// alloc分配1M内存，goroutine会阻塞，不释放内存,导致泄漏
func alloc(outCh chan<- int) {
	buf := make([]byte, 1024*1024*128)
	_ = len(buf)
	fmt.Println("alloc make buffer done")

	outCh <- 0
	fmt.Println("alloc finished")
}
